unit cfpcutils;

interface

function QuoteStr(r: string): string;
function CombineFlags(base, add: string): string;
function RemoveFileExt(FileName: string): string;

implementation

uses
  SysUtils;

function QuoteStr(r: string): string;
var i: Integer;
begin
  result:=r;

  if length(result)>0 then begin
    for i := 1 to length(result) do begin
      if result[i] in [#0..#32] then begin
        result:='"'+result+'"';
        break;
      end;
    end;
  end;
end;

function CombineFlags(base, add: string): string;

  procedure Parse(const b: string;var resultString:string);
  var i,argStart,argLen:integer;
      quote:boolean;
      arg,argQuoteCleaned,resultStringQuoteCleaned,param:string;
  begin
    resultStringQuoteCleaned:=StringReplace(resultString,'"','',[rfReplaceAll,rfIgnoreCase]);
    i:=1;
    while i<=length(b) do begin
      while (i<=length(b)) and (b[i] in [#0..#32]) do begin
        inc(i);
      end;
      quote:=false;
      argStart:=i;
      argLen:=0;
      while i<=length(b) do begin
        case b[i] of
          #0..#32:begin
            if quote then begin
              inc(i);
              inc(argLen);
            end else begin
              break;
            end;
          end;
          '"':begin
            inc(i);
            inc(argLen);
            if (i<=length(b)) and (b[i]='"') then begin
              inc(i);
              inc(argLen);
            end else begin
              quote:=not quote;
            end;
          end;
          else begin
            inc(i);
            inc(argLen);
          end;
        end;
      end;
      if argLen>0 then begin
        arg:=copy(b,argStart,argLen);
        argQuoteCleaned:=StringReplace(arg,'"','',[rfReplaceAll,rfIgnoreCase]);
        if length(argQuoteCleaned)>3 then begin
          param:=copy(argQuoteCleaned,1,3);
        end else begin
          param:=argQuoteCleaned;
        end;
        if (Pos(argQuoteCleaned, resultStringQuoteCleaned)=0) or (param='-Fu') or (param='-Fi') or (param='-Fl') then begin
          resultString:=resultString+' '+arg;
          resultStringQuoteCleaned:=resultStringQuoteCleaned+' '+argQuoteCleaned;
        end;
      end;
   end;
  end;

begin
  result:=base;
  Parse(add, result);
end;

function RemoveFileExt(FileName: string): string;
var i: integer;
begin
  i:=length(FileName);
  while (FileName[i]<>'.') do
  begin
    if (FileName[i]='\')or(i=0) then
    begin
      result:=FileName;
      Exit;
    end;
    dec(i);
  end;
  result:=copy(FileName, 1, i-1);
end;

end.
